import pygame
import math
import random

class Bird:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.radius = 15
        self.color = (255, 0, 0)  # 基础红色
        self.color_light = (255, 100, 100)  # 亮部
        self.color_dark = (200, 0, 0)  # 暗部
        self.eye_color = (255, 255, 255)
        self.beak_color = (255, 165, 0)
        self.velocity_x = 0
        self.velocity_y = 0
        self.is_flying = False
        
        # 动画参数
        self.squash = 1.0  # 形变系数
        self.rotation = 0  # 旋转角度
        self.feather_angle = 0  # 羽毛摆动角度
        self.blink_timer = 0  # 眨眼计时器
        self.wing_angle = 0  # 翅膀角度
        self.tail_wave = 0  # 尾部摆动
        self.expression = "normal"  # 表情状态
        
        # 物理参数
        self.gravity = 0.5
        self.elasticity = 0.7
        self.drag = 0.99
        
        # 羽毛效果
        self.feathers = []
        for _ in range(5):
            self.feathers.append({
                'offset_x': random.uniform(-5, 5),
                'offset_y': random.uniform(-5, 5),
                'angle': random.uniform(0, math.pi * 2),
                'size': random.uniform(3, 6)
            })
        
        # 表情定义
        self.expressions = {
            "normal": {
                "eye_scale": 1.0,
                "beak_offset": 0,
                "eyebrow_angle": 0
            },
            "determined": {
                "eye_scale": 0.8,
                "beak_offset": 2,
                "eyebrow_angle": -20
            },
            "hit": {
                "eye_scale": 1.2,
                "beak_offset": -1,
                "eyebrow_angle": 30
            },
            "dizzy": {
                "eye_scale": 0.7,
                "beak_offset": 0,
                "eyebrow_angle": 0,
                "spiral_eyes": True
            }
        }

    def update(self):
        """更新小鸟状态"""
        # 更新物理状态
        if self.is_flying:
            self.velocity_y += self.gravity
            self.velocity_x *= self.drag
            self.velocity_y *= self.drag
            
            self.x += self.velocity_x
            self.y += self.velocity_y
            
            # 根据运动方向计算旋转角度
            self.rotation = math.degrees(math.atan2(self.velocity_y, self.velocity_x))
            
            # 飞行时的形变
            speed = math.sqrt(self.velocity_x ** 2 + self.velocity_y ** 2)
            self.squash = 1.0 + min(speed * 0.02, 0.3)
            
            # 飞行时的翅膀动画
            self.wing_angle = math.sin(pygame.time.get_ticks() * 0.01) * 20
        else:
            # 站立时的动画
            self.squash = 1.0 + math.sin(pygame.time.get_ticks() * 0.005) * 0.05
            self.rotation = 0
            # 站立时的翅膀轻微摆动
            self.wing_angle = math.sin(pygame.time.get_ticks() * 0.003) * 5
        
        # 更新羽毛效果
        self.feather_angle = math.sin(pygame.time.get_ticks() * 0.003) * 15
        
        # 尾部摆动
        self.tail_wave = math.sin(pygame.time.get_ticks() * 0.004) * 10
        
        # 眨眼动画
        if self.blink_timer > 0:
            self.blink_timer -= 1
        elif random.random() < 0.005:  # 随机眨眼
            self.blink_timer = 5
        
        # 表情恢复
        if self.expression in ["hit", "determined"] and random.random() < 0.02:
            self.expression = "normal"

    def draw(self, screen):
        """绘制小鸟"""
        # 创建临时surface
        bird_surface = pygame.Surface((self.radius * 4, self.radius * 4), pygame.SRCALPHA)
        center = (bird_surface.get_width() // 2, bird_surface.get_height() // 2)
        
        # 获取表情参数
        expr = self.expressions[self.expression]
        
        # 计算形变后的尺寸
        squashed_radius_x = self.radius * self.squash
        squashed_radius_y = self.radius / self.squash
        
        # 绘制尾部羽毛
        tail_points = [
            (center[0] - squashed_radius_x * 1.2, center[1]),
            (center[0] - squashed_radius_x * 1.6, center[1] - 8 + math.sin(self.tail_wave) * 3),
            (center[0] - squashed_radius_x * 1.6, center[1] + 8 + math.sin(self.tail_wave) * 3),
        ]
        pygame.draw.polygon(bird_surface, self.color_dark, tail_points)
        
        # 绘制翅膀
        wing_points = [
            (center[0], center[1] - squashed_radius_y * 0.5),
            (center[0] + math.cos(math.radians(self.wing_angle)) * squashed_radius_x,
             center[1] - math.sin(math.radians(self.wing_angle)) * squashed_radius_y),
            (center[0] + squashed_radius_x * 0.8, center[1])
        ]
        pygame.draw.polygon(bird_surface, self.color_dark, wing_points)
        
        # 绘制身体（主要部分）
        pygame.draw.ellipse(bird_surface, self.color,
                          (center[0] - squashed_radius_x,
                           center[1] - squashed_radius_y,
                           squashed_radius_x * 2,
                           squashed_radius_y * 2))
        
        # 绘制装饰性羽毛
        for feather in self.feathers:
            angle = feather['angle'] + math.radians(self.feather_angle)
            x = center[0] + feather['offset_x'] * self.squash
            y = center[1] + feather['offset_y'] / self.squash
            size = feather['size']
            
            feather_points = [
                (x, y),
                (x + math.cos(angle) * size, y + math.sin(angle) * size),
                (x + math.cos(angle + 2.1) * size, y + math.sin(angle + 2.1) * size)
            ]
            pygame.draw.polygon(bird_surface, self.color_light, feather_points)
        
        # 绘制眼睛
        eye_offset_x = 5 * self.squash
        eye_offset_y = -3 / self.squash
        eye_size = 4 * expr["eye_scale"]
        
        if self.blink_timer > 0:
            # 眨眼状态
            pygame.draw.line(bird_surface, (0, 0, 0),
                           (center[0] + eye_offset_x - 3, center[1] + eye_offset_y),
                           (center[0] + eye_offset_x + 3, center[1] + eye_offset_y), 2)
        elif expr.get("spiral_eyes", False):
            # 眩晕效果
            for i in range(3):
                radius = (i + 1) * 2
                angle = pygame.time.get_ticks() * 0.01 + i * math.pi / 2
                spiral_x = center[0] + eye_offset_x + math.cos(angle) * radius
                spiral_y = center[1] + eye_offset_y + math.sin(angle) * radius
                pygame.draw.circle(bird_surface, (0, 0, 0),
                                (int(spiral_x), int(spiral_y)), 1)
        else:
            # 正常眼睛
            pygame.draw.circle(bird_surface, self.eye_color,
                            (int(center[0] + eye_offset_x),
                             int(center[1] + eye_offset_y)), int(eye_size))
            pygame.draw.circle(bird_surface, (0, 0, 0),
                            (int(center[0] + eye_offset_x),
                             int(center[1] + eye_offset_y)), int(eye_size * 0.5))
        
        # 绘制眉毛
        if expr["eyebrow_angle"] != 0:
            eyebrow_angle = math.radians(expr["eyebrow_angle"])
            eyebrow_length = 8
            start_x = center[0] + eye_offset_x - 4
            start_y = center[1] + eye_offset_y - 5
            end_x = start_x + math.cos(eyebrow_angle) * eyebrow_length
            end_y = start_y + math.sin(eyebrow_angle) * eyebrow_length
            pygame.draw.line(bird_surface, (0, 0, 0),
                           (start_x, start_y), (end_x, end_y), 2)
        
        # 绘制喙
        beak_offset = expr["beak_offset"]
        beak_points = [
            (center[0] + (12 + beak_offset) * self.squash, center[1]),
            (center[0] + (22 + beak_offset) * self.squash, center[1]),
            (center[0] + (12 + beak_offset) * self.squash, center[1] + 5 / self.squash)
        ]
        pygame.draw.polygon(bird_surface, self.beak_color, beak_points)
        
        # 旋转并绘制到屏幕
        if self.is_flying:
            rotated_surface = pygame.transform.rotate(bird_surface, -self.rotation)
        else:
            rotated_surface = bird_surface
        
        screen.blit(rotated_surface,
                   (self.x - rotated_surface.get_width() // 2,
                    self.y - rotated_surface.get_height() // 2))

    def launch(self, start_x, start_y, pull_x, pull_y):
        """发射小鸟"""
        self.x = start_x
        self.y = start_y
        
        dx = start_x - pull_x
        dy = start_y - pull_y
        distance = math.sqrt(dx * dx + dy * dy)
        
        # 改进的力量计算
        base_power = distance * 0.15
        power = min(base_power, 20)
        
        # 添加轻微的随机性
        random_factor = random.uniform(0.95, 1.05)
        
        self.velocity_x = dx * power * random_factor / distance
        self.velocity_y = dy * power * random_factor / distance
        self.is_flying = True
        
        # 重置形变和旋转
        self.squash = 1.0
        self.rotation = math.degrees(math.atan2(dy, dx))
        
        # 设置发射表情
        self.expression = "determined"

    def check_collision(self, game_object):
        """检查与游戏对象的碰撞"""
        closest_x = max(game_object.rect.left,
                       min(self.x, game_object.rect.right))
        closest_y = max(game_object.rect.top,
                       min(self.y, game_object.rect.bottom))
        
        distance_x = self.x - closest_x
        distance_y = self.y - closest_y
        distance = math.sqrt(distance_x * distance_x + distance_y * distance_y)
        
        if distance <= self.radius:
            # 计算碰撞伤害
            impact_speed = math.sqrt(self.velocity_x ** 2 + self.velocity_y ** 2)
            damage = impact_speed * 10
            
            # 碰撞响应
            normal_x = distance_x / distance if distance > 0 else 0
            normal_y = distance_y / distance if distance > 0 else 0
            
            # 计算反弹速度
            dot_product = (self.velocity_x * normal_x + 
                         self.velocity_y * normal_y)
            
            self.velocity_x = self.velocity_x - 2 * dot_product * normal_x
            self.velocity_y = self.velocity_y - 2 * dot_product * normal_y
            
            # 应用能量损失
            self.velocity_x *= self.elasticity
            self.velocity_y *= self.elasticity
            
            # 碰撞形变效果
            self.squash = 1.3
            
            # 设置碰撞表情
            self.expression = "hit"
            
            return damage
        return 0

    def handle_boundary_collision(self, width, height):
        """处理边界碰撞"""
        collision_occurred = False
        
        if self.x - self.radius < 0:
            self.x = self.radius
            self.velocity_x = -self.velocity_x * self.elasticity
            collision_occurred = True
        elif self.x + self.radius > width:
            self.x = width - self.radius
            self.velocity_x = -self.velocity_x * self.elasticity
            collision_occurred = True
        
        if self.y - self.radius < 0:
            self.y = self.radius
            self.velocity_y = -self.velocity_y * self.elasticity
            collision_occurred = True
        elif self.y + self.radius > height:
            self.y = height - self.radius
            self.velocity_y = -self.velocity_y * self.elasticity
            self.velocity_x *= 0.95  # 地面摩擦
            collision_occurred = True
        
        if collision_occurred:
            # 碰撞形变效果
            self.squash = 1.2
            # 设置碰撞表情
            self.expression = "hit"
            
        # 检查是否停止运动
        if (abs(self.velocity_x) < 0.1 and 
            abs(self.velocity_y) < 0.1 and 
            self.y > height - self.radius - 1):
            self.expression = "dizzy"